package com.zoe.onelink.core.web.jackson.provider;

import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.zoe.onelink.core.web.jackson.serializer.JacksonNullToEmptyValueSerializer;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * <p>标题: 脱敏策略器</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-09-06
 */
@Slf4j
public class OnelinkSerializerProvider extends DefaultSerializerProvider {

    private static final long serialVersionUID = 2628135786365301043L;

    private static final JacksonNullToEmptyValueSerializer NULL_TO_EMPTY_SERIALIZER = new JacksonNullToEmptyValueSerializer();

    private final List<Class<?>> resolveTypes;

    public OnelinkSerializerProvider(List<Class<?>> resolveTypes) {
        super();
        this.resolveTypes = resolveTypes;
    }

    public OnelinkSerializerProvider(OnelinkSerializerProvider provider, List<Class<?>> resolveTypes) {
        super(provider);
        this.resolveTypes = resolveTypes;
    }

    protected OnelinkSerializerProvider(SerializerProvider provider, SerializationConfig config,
                                        SerializerFactory factory, List<Class<?>> resolveTypes) {
        super(provider, config, factory);
        this.resolveTypes = resolveTypes;
    }

    @Override
    public DefaultSerializerProvider copy() {
        if (getClass() != OnelinkSerializerProvider.class) {
            return super.copy();
        }
        return new OnelinkSerializerProvider(this, this.resolveTypes);
    }

    @Override
    public OnelinkSerializerProvider createInstance(SerializationConfig config, SerializerFactory factory) {
        return new OnelinkSerializerProvider(this, config, factory, this.resolveTypes);
    }

    @Override
    public JsonSerializer<Object> findNullValueSerializer(BeanProperty property) throws JsonMappingException {
        if (this.resolveTypes == null) {
            return super.findNullValueSerializer(property);
        }
        Class<?> rawClass = property.getType().getRawClass();
        for (Class<?> resolveType : this.resolveTypes) {
            if (resolveType.isAssignableFrom(rawClass)) {
                if (log.isDebugEnabled()) {
                    log.debug("[Jackson Serializer] Raw class Type [{}] is matched , use NULL_TO_EMPTY_SERIALIZER", rawClass);
                }
                return NULL_TO_EMPTY_SERIALIZER;
            }
        }
        return super.findNullValueSerializer(property);
    }

}